#include "logger.h"

Logger* Logger::instance = nullptr;
QMutex Logger::mutex;

Logger* Logger::getInstance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new Logger();
        }
    }
    return instance;
}

Logger::Logger(QObject *parent) : QObject(parent), 
    currentLevel(LogLevel::Info), 
    callback(nullptr),
    maxLogEntries(100)  // 保存最近100条日志
{
    // 默认日志输出到控制台
}

Logger::~Logger()
{
    if (logFile.isOpen()) {
        logStream.flush();
        logFile.close();
    }
}

void Logger::log(LogLevel level, const QString &message)
{
    if (level < currentLevel) {
        return;
    }

    QString logMessage = QString("[%1] [%2]: %3")
                          .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"))
                          .arg(levelToString(level))
                          .arg(message);

    QMutexLocker locker(&mutex);
    
    // 添加到内存中的日志条目
    logEntries.append(logMessage);
    while (logEntries.size() > maxLogEntries) {
        logEntries.removeFirst();
    }
    
    // 输出到日志文件
    if (logFile.isOpen()) {
        logStream << logMessage << "\n";
        logStream.flush();
    }
    
    // 转换为Qt消息类型
    QtMsgType msgType;
    switch (level) {
    case LogLevel::Debug:
        msgType = QtDebugMsg;
        break;
    case LogLevel::Info:
        msgType = QtInfoMsg;
        break;
    case LogLevel::Warning:
        msgType = QtWarningMsg;
        break;
    case LogLevel::Error:
        msgType = QtCriticalMsg;
        break;
    case LogLevel::Fatal:
        msgType = QtFatalMsg;
        break;
    default:
        msgType = QtInfoMsg;
        break;
    }
    
    // 调用回调函数
    if (callback) {
        callback(msgType, message);
    }
    
    // 同时输出到控制台
    switch (level) {
    case LogLevel::Debug:
        qDebug() << logMessage;
        break;
    case LogLevel::Info:
        qInfo() << logMessage;
        break;
    case LogLevel::Warning:
        qWarning() << logMessage;
        break;
    case LogLevel::Error:
    case LogLevel::Fatal:
        qCritical() << logMessage;
        break;
    }
}

QStringList Logger::getLatestEntries()
{
    QMutexLocker locker(&mutex);
    
    // 返回最新日志条目的副本并清空当前列表
    QStringList result = logEntries;
    logEntries.clear();
    return result;
}

void Logger::setLogFile(const QString &filePath)
{
    QMutexLocker locker(&mutex);
    
    // 如果已经有打开的日志文件，先关闭
    if (logFile.isOpen()) {
        logStream.flush();
        logFile.close();
    }
    
    logFile.setFileName(filePath);
    if (logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        logStream.setDevice(&logFile);
    } else {
        qCritical() << "无法打开日志文件:" << filePath;
    }
}

void Logger::setLogLevel(LogLevel level)
{
    currentLevel = level;
}

void Logger::setCallback(const LogCallback &callback)
{
    QMutexLocker locker(&mutex);
    this->callback = callback;
}

QString Logger::levelToString(LogLevel level)
{
    switch (level) {
    case LogLevel::Debug:
        return "调试";
    case LogLevel::Info:
        return "信息";
    case LogLevel::Warning:
        return "警告";
    case LogLevel::Error:
        return "错误";
    case LogLevel::Fatal:
        return "致命错误";
    default:
        return "未知";
    }
} 